package com.tbr.usercenter.exception;

import com.tbr.usercenter.common.BaseResponse;
import com.tbr.usercenter.common.ErrorCode;
import com.tbr.usercenter.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 捕获来自spring异常的全局拦截器，将异常信息进行封装，隐藏里面的报错具体细节，返回给前端一个错误信息以及描述
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 捕获BusinessException异常如参数格式，越权等等，利用Spring AOP
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public BaseResponse businessExceptionHandler(BusinessException e){
        log.error("businessException: "+e.getMessage(),e);
        return ResultUtils.error(e.getCode(),e.getMessage(),"");
    }

    /**
     * 捕获RuntimeException，即系统内部错误，捕获后进行封装
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public BaseResponse runtimeExceptionHandler(RuntimeException e){
        log.error("runtimeException",e);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR,e.getMessage(),"");
    }
}
